//
// Created by 25446 on 2023/3/10.
//

#include "graph.h"

Node *create_graph(char *words[], int len) {
    Node *nodes = (Node *) malloc((len + 5) * sizeof(Node));

    if (nodes == nullptr) return nullptr;
    int idx = 0;
    for (int i = 1; i <= len; i++) {
        char *word = words[i];
        auto tmp = new Node(word, i - 1);
        nodes[idx++] = *tmp;
    }
    for (int i = 0; i < len; i++) {
        int h = nodes[i].get_head();
        int t = nodes[i].get_tail();
        for (int j = 0; j < len; j++) {
            if (j != i) {
                if (t == nodes[j].get_head()) {
                    nodes[j].ind_inc();
                    nodes[i].add(j);
                }
            }
        }
    }
    return nodes;
}

int topo_sort(Node *nodes, int len, int *topo_list) { //拓扑排序顺便检测环路
    std::queue<int> que;
    int cnt = 0;

    for (int i = 0; i < len; i++) {
        if (nodes[i].get_ind() == 0) {
            que.push(i);
        }
    }
    while (!que.empty()) {
        int top = que.front();
        que.pop();
        topo_list[cnt++] = top;
        for (int i = 0; i < nodes[top].get_oud(); i++) {
            nodes[nodes[top].get_to(i)].ind_dec();
            if (nodes[nodes[top].get_to(i)].get_ind() == 0) {
                que.push(nodes[top].get_to(i));
            }
        }
    }
    if (cnt != len) {
        return -1;
    } else {
        return 0;
    }
}
